package com.zhiwang.planet.aop.net

import android.util.Log
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.event.AuthExpireEvent
import com.zhiwang.planet.event.LogoutEvent
import com.zhiwang.planet.mvvm.viewmodel.NetWorkViewModel
import com.zhiwang.planet.ui.BaseActivity
import com.zhiwang.planet.ui.BaseFragment
import com.zhiwang.planet.util.AppHelper
import com.zhiwang.planet.util.AppUtil
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.TokenManager
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.greenrobot.eventbus.EventBus

//network annotation for methods that associated withDrawPresenter network
@Target(AnnotationTarget.FUNCTION)
annotation class NetWorkRequired

@Target(AnnotationTarget.FUNCTION)
annotation class LoginRequired


@Target(AnnotationTarget.FUNCTION)
annotation class SimCardRequired


@Aspect
open class NetWorkAspect {

    private val TAG = "NetWorkAspectEx"

    @Around("execution(@com.zhiwang.planet.aop.net.NetWorkRequired  * *(..))")
    @Throws(Throwable::class)
    fun networkRequired(proceedingJoinPoint: ProceedingJoinPoint) {
        if (NetWorkViewModel.connected.get())
            proceedingJoinPoint.proceed()
        else
            Toaster.message(R.string.network_error_serious_hint)
    }

    @Around("execution(@com.zhiwang.planet.aop.net.SimCardRequired  * *(..))")
    @Throws(Throwable::class)
    fun simCardRequired(proceedingJoinPoint: ProceedingJoinPoint) {

        if (AppUtil.checkSimInsert()||AppHelper.isDev())
            proceedingJoinPoint.proceed()
        else
            Toaster.message("未插入 sim 卡")
    }
}


@Aspect
open class LoginAspect {

    private val TAG = "NetWorkAspectEx"

    @Around("execution(@com.zhiwang.planet.aop.net.LoginRequired  * *(..))")
    @Throws(Throwable::class)
    fun loginRequired(jp: ProceedingJoinPoint) {
        if (BuildConfig.DEBUG)
//            Log.i(TAG, "loginRequired 拦截: ${jp.target}   ${jp.`this`}  ${jp.signature}")
        if (TokenManager.isLoginValid().not()) {
            if (jp.`this` is BaseFragment) {
                val fragment = jp.`this` as BaseFragment
                fragment.onAuthExpired()
            } else if (jp.`this` is BaseActivity) {
                val activity = jp.`this` as BaseActivity
                activity.onAuthExpired()
            }else{

                EventBus.getDefault().post(AuthExpireEvent)
            }
        } else jp.proceed()
    }
}
